package com.yuzhitong.shapi.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.bytedance.sdk.dp.DPSdk;
import com.bytedance.sdk.dp.DPWidgetNewsParams;
import com.bytedance.sdk.dp.IDPNewsListener;
import com.bytedance.sdk.dp.IDPWidget;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.flyco.tablayout.SlidingTabLayout;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.KsHorizontalFeedPage;
import com.kwad.sdk.api.KsLoadManager;
import com.kwad.sdk.api.KsScene;
import com.kwad.sdk.api.KsTubePage;
import com.umeng.commonsdk.UMConfigure;
import com.yuzhitong.shapi.BuildConfig;
import com.yuzhitong.shapi.R;
import com.yuzhitong.shapi.activity.SettingActivity;
import com.yuzhitong.shapi.activity.WebPageActivity;
import com.yuzhitong.shapi.base.BaseMvpFragment;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.bean.HomeListBean;
import com.yuzhitong.shapi.contract.HomeContract;
import com.yuzhitong.shapi.presenter.HomePresenter;
import com.yuzhitong.shapi.util.AdUtilManage;
import com.yuzhitong.shapi.util.AppUtil;
import com.yuzhitong.shapi.util.GlideUtil;
import com.yuzhitong.shapi.util.LoggerUtil;
import com.yuzhitong.shapi.util.TTAdManagerHolder;
import com.yuzhitong.shapi.util.UiUtil;
import com.yuzhitong.shapi.widget.AgreementDialog;
import com.yuzhitong.shapi.widget.HintDialog;

import java.util.Arrays;
import java.util.List;

import a.a.a.MyApplication;

public class HomeFragment extends BaseMvpFragment<HomePresenter> implements HomeContract.View {

    private final int RECOMMEND_POSITION = 0;
    private final int HOT_POSITION = 1;
    private final int VIDEO_POSITION = 2;
    private final int BOOK_POSITION = 3;


    private CoordinatorLayout rlFragmentPage;
    private EditText etSearch;
    private LinearLayout llSearchIcon;
    private LinearLayout llNavigationBox1;
    private LinearLayout llNavigationBox2;
    private RelativeLayout flAdBox;

    private String searchUrl;
    private int heightPixels;
    private boolean imIsShow;

    private long loadAdTime = 0;

    private AdUtilManage adUtilManage;

    private long clickTime = -1;
    private RelativeLayout rlSearchInputBox;
    private int clickNumberLimit = 0;
    private LinearLayout llSettingBox;
    private SlidingTabLayout tlFragmentTitle;
    private ViewPager vpFragmentBox;

    // 标题
    private final String[] tabs = {"推荐", "热榜", "视频", "短剧"};
    private List<Fragment> tabFragmentList;
    private KsLoadManager loadManager;
    private RelativeLayout rlTtNewsBox;

    private Fragment csjFragment;

    public static HomeFragment newInstance() {

        Bundle args = new Bundle();

        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public HomeFragment() {
    }

    @Override
    protected void initView() {
        setContentViewId(R.layout.fragment_home);
        rlFragmentPage = findViewById(R.id.cl_fragment_page);
        llSettingBox = findViewById(R.id.ll_setting_box);
        flAdBox = findViewById(R.id.fl_ad_box);
        etSearch = (EditText) findViewById(R.id.et_search);
        llNavigationBox1 = (LinearLayout) findViewById(R.id.ll_navigation_box1);
        llNavigationBox2 = (LinearLayout) findViewById(R.id.ll_navigation_box2);
        llSearchIcon = findViewById(R.id.ll_search_icon);
        rlSearchInputBox = findViewById(R.id.rl_search_input_box);
        tlFragmentTitle = findViewById(R.id.tl_fragment_title);
        vpFragmentBox = findViewById(R.id.vp_fragment_box);
        rlTtNewsBox = findViewById(R.id.rl_tt_news_box);

        rlFragmentPage.setPadding(
                rlFragmentPage.getPaddingLeft(),
                rlFragmentPage.getPaddingTop() + UiUtil.getStatusBarHeight(getContext()),
                rlFragmentPage.getPaddingRight(),
                rlFragmentPage.getPaddingBottom()
        );


        //        LoggerUtil.e("屏幕宽度app:" + getActivity().getApplicationContext().getResources().getDisplayMetrics().xdpi);
        //        LoggerUtil.e("屏幕宽度act:" + getActivity().getResources().getDisplayMetrics().xdpi);
        //
        //
        //        TextView tvSetting = findViewById(R.id.tv_setting_text);
        //        tvSetting.setText(String.valueOf(getActivity().getApplicationContext().getResources().getDisplayMetrics().xdpi));


        if (MyApplication.isOpenSearch()) {
            rlSearchInputBox.setVisibility(View.VISIBLE);
        }


        // 点击自动选中 xml中android:selectAllOnFocus="true"
        etSearch.setSelectAllOnFocus(true);
        etSearch.setOnFocusChangeListener((v, hasFocus) -> llSearchIcon.setVisibility(hasFocus ? View.VISIBLE : View.GONE));

        etSearch.setOnEditorActionListener((textView, i, keyEvent) -> {
            // 搜索或回车
            if (i == EditorInfo.IME_ACTION_SEARCH || (keyEvent != null && keyEvent.getAction() == KeyEvent.KEYCODE_ENTER)) {
                String search = etSearch.getText().toString();
                handleSearchTet(search);
                return true;
            }
            return false;
        });

        llSearchIcon.setOnClickListener((v) -> {
            String search = etSearch.getText().toString();
            handleSearchTet(search);
        });

        llSettingBox.setOnClickListener((v) -> {
            startActivity(new Intent(getActivity(), SettingActivity.class));
        });
        presenter.getSearchUrl(null);

        // 获取屏幕宽度
        WindowManager manager = requireActivity().getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        heightPixels = outMetrics.heightPixels;

        etSearch.getViewTreeObserver().addOnGlobalLayoutListener(() -> {

            //获取当前根视图在屏幕上显示的大小
            Rect r = new Rect();
            etSearch.getWindowVisibleDisplayFrame(r);

            // 判断是否显示键盘
            if (heightPixels - r.bottom > 300) {
                imIsShow = true;
            }
            // 判断显示高度是否等于屏幕高度  键盘显示转为隐藏
            if (heightPixels == r.bottom && imIsShow) {
                imIsShow = false;
                etSearch.clearFocus();
            }

        });

        //        ivAdBig.setVisibility(MyApplication.isOpenAd() ? View.VISIBLE : View.GONE);


        //        for (String tab : tabs) {
        //            tlFragmentTitle.addTab(tlFragmentTitle.newTab().setText(tab));
        //        }

        tabFragmentList = Arrays.asList(null, null, null, null);

        if (DPSdk.factory() != null) {
            IDPWidget newsTabs = DPSdk.factory().createNewsOneTab(DPWidgetNewsParams.obtain().listener(new IDPNewsListener() {}));
            FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
            fragmentTransaction.add(R.id.rl_tt_news_box, csjFragment = newsTabs.getFragment());
            fragmentTransaction.commit();
        }


//        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                addKsContent();
//            }
//        }, 3000);

    }

    @Override
    public void onResume() {
        super.onResume();
        //        showHintDialog();
        if (csjFragment == null) {
            if (DPSdk.factory() != null) {
                IDPWidget newsTabs = DPSdk.factory().createNewsTabs(DPWidgetNewsParams.obtain().listener(new IDPNewsListener() {}));
                FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
                fragmentTransaction.add(R.id.rl_tt_news_box, csjFragment = newsTabs.getFragment());
                fragmentTransaction.commit();
            }
        }
    }

    private void showHintDialog() {
        if (!MyApplication.isAgree()) {
            new HintDialog(getActivity())
                    .setTitle("同意用户协议未同意")
                    .setText("同意用户协议可以为您提供更优质、安全的个性化服务内容，请在点击确定后选择同意。")
                    .setOnClickBtnListener(new HintDialog.OnClickBtnListener() {
                        @Override
                        public void onDismiss() {

                        }

                        @Override
                        public void onConfirm() {
                            showAgreement();
                        }
                    }).show();
        }
    }


    private void showAgreement() {
        AgreementDialog agreementDialog = new AgreementDialog(getActivity());
        agreementDialog.setOnClickBtnListener(new AgreementDialog.OnClickBtnListener() {
            @Override
            public void onDismiss() {
            }

            @Override
            public void onConfirm() {
                presenter.getAdState();
                //友盟正式初始化
                UMConfigure.init(getActivity().getApplicationContext(), Contents.YM_SDK_ID, BuildConfig.CHANNEL_NAME, UMConfigure.DEVICE_TYPE_PHONE, "");
                TTAdManagerHolder.get().init(getActivity().getApplicationContext(), new TTAdSdk.InitCallback() {
                    @Override
                    public void success() {
                        LoggerUtil.i("穿山甲SDK初始化成功");
                    }

                    @Override
                    public void fail(int i, String s) {
                        LoggerUtil.i("穿山甲SDK初始化失败");
                    }
                });
                MyApplication.initDpSdk();
                MyApplication.initBookDpSdk();
            }
        });
        agreementDialog.show();
    }

    /**
     * 加载快手内容
     */
    private void addKsContent() {
        if (!MyApplication.isOpenAdContent()) {
            return;
        }
    /*
    横版图文
     */
        // 内容id

        loadManager = KsAdSDK.getLoadManager();
        if (loadManager == null) {
            return;
        }
        KsHorizontalFeedPage ksHorizontalFeedPage = loadManager.loadHorizontalNewsFeedPage(new
                KsScene.Builder(Contents.KS_SDK_IMG_TEXT_ID).build());
        Fragment fragment = ksHorizontalFeedPage.getFragment();
        tabFragmentList.set(RECOMMEND_POSITION, fragment);

        tabFragmentList.set(HOT_POSITION, HotFragment.newInstance());

        IDPWidget newsTabs = DPSdk.factory().createNewsOneTab(DPWidgetNewsParams.obtain().setDisableLuckView(false).listener(new IDPNewsListener() {}));
        tabFragmentList.set(VIDEO_POSITION, newsTabs.getFragment());

        KsScene scene = new KsScene.Builder(Contents.KS_SDK_VIDEO_ID)
                .needShowMiniWindow(false)
                .build();
        KsTubePage ksTubePage = loadManager.loadTubePage(scene, false);
        tabFragmentList.set(BOOK_POSITION, ksTubePage.getFragment());

        vpFragmentBox.setOffscreenPageLimit(3);
        vpFragmentBox.setAdapter(new FragmentPagerAdapter(getChildFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return tabFragmentList.get(position);
            }

            @Override
            public int getCount() {
                return 4;
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return tabs[position];
            }
        });

        tlFragmentTitle.setViewPager(vpFragmentBox);
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {
            if (System.currentTimeMillis() - loadAdTime > Contents.AD_SHOW_TIME) {
                loadAdTime = System.currentTimeMillis();
                if (adUtilManage != null) {
                    AdUtilManage.destroy(adUtilManage);
                }
                adUtilManage = AdUtilManage.initShow(getActivity(), flAdBox, Contents.AD_TT_SDK_HOME_ID);
            }

//            if (loadManager == null) {
//                addKsContent();
//            }
        }
    }

    /**
     * 处理搜索框内容
     *
     * @param text 搜索框内容
     */
    private void handleSearchTet(String text) {
        String url = AppUtil.handleSearchText(searchUrl, text);
        if (url == null) {
            return;
        }
        gotoWebPage(url);
    }

    @Override
    protected void initPresenter() {
        presenter = new HomePresenter();
        presenter.attachView(this);
    }

    @Override
    protected void initData() {
        presenter.getHomeList();
        presenter.getAdState();

        loadAdTime = System.currentTimeMillis();
        adUtilManage = AdUtilManage.initShow(getActivity(), flAdBox, Contents.AD_TT_SDK_NAVIGATION_ID);
    }

    @Override
    public void searchUrl(String url) {
        searchUrl = url;
        MyApplication.aCache.put(Contents.CACHE_KEY_SEARCH_URL, url);
    }

    @Override
    public void searchUrlEmpty() {
        searchUrl = null;
        MyApplication.aCache.put(Contents.CACHE_KEY_SEARCH_URL, "");
    }

    @Override
    public void showHomeList(List<HomeListBean> homeListBeans) {
        if (homeListBeans == null || homeListBeans.size() == 0) {
            llNavigationBox1.setVisibility(View.GONE);
            llNavigationBox2.setVisibility(View.GONE);
            return;
        }
        if (homeListBeans.size() < 5) {
            llNavigationBox2.setVisibility(View.GONE);
        }

        for (int i = 0; i < homeListBeans.size() && i < 10; i++) {
            HomeListBean homeListBean = homeListBeans.get(i);
            if (i < 5) {
                addNavigationBox(llNavigationBox1, homeListBean);
            } else {
                addNavigationBox(llNavigationBox2, homeListBean);
            }
        }
    }


    /**
     * 添加导航
     *
     * @param boxView      需要添加到的View
     * @param homeListBean 数据
     */
    private void addNavigationBox(LinearLayout boxView, HomeListBean homeListBean) {
        LinearLayout linearLayout = (LinearLayout) View.inflate(getContext(), R.layout.layout_navigation_box, null);
        ImageView icon = linearLayout.findViewById(R.id.iv_navi_icon);
        TextView textView = linearLayout.findViewById(R.id.tv_navi_text);
        GlideUtil.loadCircle(icon, homeListBean.getIconUrl());
        textView.setText(homeListBean.getName());

        linearLayout.setOnClickListener(view -> {

            long timeout = MyApplication.getHomeClickTimeout();
            String clickNumberStr = MyApplication.aCache.getAsString(Contents.CACHE_KEY_AGREE_AGREEMENT);
            int clickNumber = -1;
            try {
                clickNumber = Integer.parseInt(clickNumberStr);
            } catch (NumberFormatException ignored) {
                LoggerUtil.e("点击次数限制转换int错误：" + clickNumberStr);
            }
            if (timeout > 0 && System.currentTimeMillis() - clickTime > timeout && clickNumber > 0 && clickNumberLimit < clickNumber) {
                clickNumberLimit++;
                clickTime = System.currentTimeMillis();

                gotoWebPage(homeListBean.getLinkUrl(), true);
                //
                //                AdVideoUtilManage.initNewShow(getActivity(), true, new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
                //                            @Override
                //                            public void onAdShow() {
                //
                //                            }
                //
                //                            @Override
                //                            public void onAdVideoBarClick() {
                //
                //                            }
                //
                //                            @Override
                //                            public void onAdClose() {
                //                                gotoWebPage(homeListBean.getLinkUrl());
                //                            }
                //
                //                            @Override
                //                            public void onVideoComplete() {
                //                                gotoWebPage(homeListBean.getLinkUrl());
                //                            }
                //
                //                            @Override
                //                            public void onSkippedVideo() {
                //                            }
                //                        },
                //                        new AdVideoUtilManage.AdLoadListener() {
                //                            @Override
                //                            public void success() {
                //
                //                            }
                //
                //                            @Override
                //                            public void error() {
                //                                gotoWebPage(homeListBean.getLinkUrl());
                //                            }
                //                        });


            } else {
                gotoWebPage(homeListBean.getLinkUrl());
            }


        });


        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                UiUtil.dpToPx(requireContext(), 70)
                , LinearLayout.LayoutParams.MATCH_PARENT);
        boxView.addView(linearLayout, layoutParams);
    }

    /**
     * 加载网页
     *
     * @param url 网页地址
     */
    private void gotoWebPage(String url) {
        gotoWebPage(url, false);
    }

    /**
     * 加载网页
     *
     * @param url 网页地址
     */
    private void gotoWebPage(String url, boolean showAd) {
        Intent intent = new Intent(getActivity(), WebPageActivity.class);
        intent.putExtra(Contents.INTENT_H5_URL, url);
        intent.putExtra(Contents.INTENT_H5_SHOW_AD, showAd);
        startActivity(intent);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 300 && resultCode == -1) {
            if (data == null) {
                return;
            }
            String url = data.getStringExtra(Contents.INTENT_H5_URL);
            if (url == null) {
                return;
            }
            gotoWebPage(url);
        }
    }
}